package edu.usm.cs.roberge.views;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import edu.usm.cs.roberge.NewsReaderImpl;
import edu.usm.cs.roberge.NewsReaderModel;
import edu.usm.cs.roberge.workers.FetchNewsGroupWorker;

public class MainView {

	private static final String NEWSREADER_DATA_FILE_NAME = "newsreader.data";
	private JFrame frmUsmNewsReader;
	private JTextField newsGroupServerTxt;
	private JLabel lblNewLabel;
	private JTable table;
	private NewsGroupTableModel model;
	private JLabel newsGroupCnt;
	private JTextField textField;
	private NewsReaderImpl impl;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			
		}
		
		File file = new File(NEWSREADER_DATA_FILE_NAME);
		NewsReaderModel persistedModel = null;
		
		if (file.exists()) {
			try {
				ObjectInputStream in = new ObjectInputStream(new FileInputStream(NEWSREADER_DATA_FILE_NAME));
				persistedModel = (NewsReaderModel) in.readObject();
			} catch (FileNotFoundException e) {
				
			} catch (IOException e) {

			} catch (ClassNotFoundException e) {

			}
		}
		
		if (persistedModel == null) {
			persistedModel = new NewsReaderModel();
		}		
		
		final NewsReaderModel dataModel = persistedModel;
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainView window = new MainView(dataModel);
					window.frmUsmNewsReader.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainView(NewsReaderModel dataModel) {
		initialize(dataModel);
	}

	/**
	 * Initialize the contents of the frame.
	 * @param dataModel 
	 */
	private void initialize(final NewsReaderModel dataModel) {
		frmUsmNewsReader = new JFrame();
		frmUsmNewsReader.setTitle("USM News Reader");
		frmUsmNewsReader.setBounds(100, 100, 679, 557);
		frmUsmNewsReader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		model = new NewsGroupTableModel(dataModel);
		
		JButton btnFetchNewsGroups = new JButton("Fetch News Groups");
		
		btnFetchNewsGroups.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				impl = new NewsReaderImpl(newsGroupServerTxt.getText());
				newsGroupCnt.setText("Please wait, retrieving news groups...");
				new FetchNewsGroupWorker(impl, dataModel, model) {

					@Override
					protected void done() {
						newsGroupCnt.setText("Found " + tableModel.getRowCount() + " news groups");
					}
					
				}.execute();
			}
		});
		
		newsGroupServerTxt = new JTextField();
		newsGroupServerTxt.setText("freenews.netfront.net");
		newsGroupServerTxt.setColumns(10);
		
		lblNewLabel = new JLabel("Address to News Group Server:");
		
		JScrollPane scrollPane = new JScrollPane();
		
		newsGroupCnt = new JLabel("");
		
		final JLabel lblFilterListingeg = new JLabel("Filter Results (e.g. linux):");
		
		textField = new JTextField();
		textField.setColumns(10);
		
		JButton btnFilterResults = new JButton("Filter Results");
		btnFilterResults.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				model.setFilter(textField.getText());
			}
		});
		
		JButton btnViewFavoriteNews = new JButton("View Favorite News Groups");
		btnViewFavoriteNews.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (impl == null) {
					impl = new NewsReaderImpl(newsGroupServerTxt.getText());
				}
				new FavoritesView(dataModel, impl).setVisible(true);
			}
		});
		
		JButton btnSaveAllData = new JButton("Save All Data");
		btnSaveAllData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(NEWSREADER_DATA_FILE_NAME));
					out.writeObject(dataModel);
				} catch (FileNotFoundException e) {

				} catch (IOException e) {

				}
			}
		});
		
		GroupLayout groupLayout = new GroupLayout(frmUsmNewsReader.getContentPane());
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(27)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 634, Short.MAX_VALUE)
						.addComponent(lblFilterListingeg)
						.addComponent(lblNewLabel)
						.addComponent(textField, GroupLayout.PREFERRED_SIZE, 162, GroupLayout.PREFERRED_SIZE)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(btnFetchNewsGroups)
									.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
									.addComponent(btnSaveAllData))
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(btnFilterResults)
									.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
									.addComponent(btnViewFavoriteNews))
								.addComponent(newsGroupServerTxt, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 385, GroupLayout.PREFERRED_SIZE))
							.addGap(105)
							.addComponent(newsGroupCnt)))
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(19)
					.addComponent(lblNewLabel)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(newsGroupServerTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(newsGroupCnt))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnFetchNewsGroups)
						.addComponent(btnSaveAllData))
					.addGap(18)
					.addComponent(lblFilterListingeg)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnFilterResults)
						.addComponent(btnViewFavoriteNews))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
					.addContainerGap())
		);
		
		table = new JTable();
		scrollPane.setViewportView(table);
		table.setModel(model);
		table.getColumnModel().getColumn(0).setPreferredWidth(89);
		table.getColumnModel().getColumn(1).setPreferredWidth(297);
		table.getColumnModel().getColumn(2).setPreferredWidth(120);
		table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				model.rowSelected(table.getSelectedColumn(), table.getSelectedRow());
				table.getSelectionModel().clearSelection();
			}
		});
		frmUsmNewsReader.getContentPane().setLayout(groupLayout);
	}
}
